package com.example.weatherapp1.presentation.view.adapter


import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.weatherapp1.R
import com.example.weatherapp1.data.model.SkyConItem
import com.example.weatherapp1.presentation.viewmodel.WeatherViewModel
import java.text.SimpleDateFormat
import java.util.*

class ForecastAdapter(
    private val viewModel: WeatherViewModel
) : ListAdapter<SkyConItem, ForecastAdapter.ForecastViewHolder>(ForecastDiffCallback()) {

    inner class ForecastViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val dateTextView: TextView = itemView.findViewById(R.id.dateTextView)
        private val weatherIconImageView: ImageView = itemView.findViewById(R.id.weatherIconImageView)
        private val weatherDescTextView: TextView = itemView.findViewById(R.id.weatherDescTextView)

        fun bind(skyConItem: SkyConItem) {
            // 格式化日期
            val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            val date = sdf.parse(skyConItem.date)
            val outputFormat = SimpleDateFormat("MM-dd", Locale.getDefault())
            dateTextView.text = outputFormat.format(date ?: Date())

            // 设置天气图标和描述
            weatherIconImageView.setImageResource(
                viewModel.getWeatherIcon(skyConItem.value)
            )
            weatherDescTextView.text = viewModel.getWeatherDescription(skyConItem.value)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ForecastViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_forecast, parent, false)
        return ForecastViewHolder(view)
    }

    override fun onBindViewHolder(holder: ForecastViewHolder, position: Int) {
        holder.bind(getItem(position))
    }
}

class ForecastDiffCallback : DiffUtil.ItemCallback<SkyConItem>() {
    override fun areItemsTheSame(oldItem: SkyConItem, newItem: SkyConItem): Boolean {
        return oldItem.date == newItem.date
    }

    override fun areContentsTheSame(oldItem: SkyConItem, newItem: SkyConItem): Boolean {
        return oldItem == newItem
    }
}
